import React, { Component } from 'react'
import { Form, Input, Button,message} from 'antd';
import axios from 'axios';
export default class Login extends Component {
  login(user){
     axios.post('/api/login',user).then((res)=>{
       console.log('/api/login',res);
       if(res.data.code===0){
          // 登录成功
          message.success(res.data.message);
          // 保存token
          sessionStorage.setItem("token",res.data.token);
          sessionStorage.setItem("username",user.username);
          this.props.history.push('/admin');


       }else{
         // 登录失败 （用户名密码错误）
        message.error(res.data.message);

        // 清空token
        sessionStorage.removeItem("token"); 
        sessionStorage.removeItem("username");
       }
     })
  }
  render() {

    const layout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const tailLayout = {
      wrapperCol: {
        offset: 8,
        span: 16,
      },
    };


    const onFinish = (values) => {
      console.log('Success:', values);
      this.login(values);
    };

    const onFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
    };


    return (
      <div>
        <div className="loginbox">
        <Form
          {...layout}
          name="loginfrom"
          initialValues={{
           
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入你的用户名!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入你的密码!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

         

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              登录
        </Button>
          </Form.Item>
        </Form>
        </div>
      </div>
    )
  }
}